import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:queue_flutter/queue_obj.dart';

import 'const.dart';

class Api {
  final CONST = Const();

  Future<QueueList?> getQueue(String userId) async {
    final response =
        await http.get(Uri.parse("${CONST.ENDPOINT}/queue/$userId"));
    if (response.statusCode == 200) {
      return QueueList.fromJson(
          jsonDecode(response.body) as Map<String, dynamic>);
    } else if (response.statusCode == 404) {
      return null;
    } else {
      throw Exception('Failed to get queue list.');
    }
  }

  Future<QueueList> createQueue(String name, String userId) async {
    Map<String, String> payload = {
      'name': name,
    };
    final response =
        await http.post(Uri.parse("${CONST.ENDPOINT}/queue/$userId/"),
            headers: <String, String>{
              'Content-Type':
                  'application/x-www-form-urlencoded; charset=UTF-8',
            },
            body: payload);

    if (response.statusCode == 200) {
      return QueueList.fromJson(
          jsonDecode(response.body) as Map<String, dynamic>);
    } else {
      throw Exception('Failed to create queue list.');
    }
  }

  Future<bool> deleteQueue(String userId) async {
    final response =
        await http.delete(Uri.parse("${CONST.ENDPOINT}/queue/$userId/"));
    if (response.statusCode == 204) {
      return true;
    } else {
      throw Exception('Cannot delete queue.');
    }
  }

  Future<QueueList> updateCaller(
      String code, String userId, String bulletin) async {
    Map<String, String> payload = {
      'uuid': userId,
      'bulletin': bulletin,
    };
    final response =
        await http.post(Uri.parse("${CONST.ENDPOINT}/queue/$code/caller/"),
            headers: <String, String>{
              'Content-Type':
                  'application/x-www-form-urlencoded; charset=UTF-8',
            },
            body: payload);

    if (response.statusCode == 200) {
      return QueueList.fromJson(
          jsonDecode(response.body) as Map<String, dynamic>);
    } else {
      throw Exception('Failed to update caller.');
    }
  }
}
